package com.carworld.controller;

import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.carworld.config.BaseController;
import com.carworld.config.UserInter;
import com.carworld.model.*;
import com.carworld.utils.DicUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheKit;
import org.apache.commons.lang3.time.DateUtils;


public class VIPCardController extends BaseController {

	private synchronized  Date getDate(){
		return new Date();
	}

	//我的会员卡页面
	public void mycard(){
		render("/pages/page_dividend/trueMyVipCard.html");
	}

	/**
	 * 获取用户卡信息
	 */
	public void getCardInfo()
	{
		String userId = getUserCookie();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("card", Card.dao.findCardByUserId(userId));
		renderJson(jsonObject);
	}


    //青铜会员注册
    public void verifyShareHolder(){
		String name=getPara("name");
		String phone=getPara("phone");
		String userId = getUserCookie();
		//验证身份
		SysUser uu=SysUser.dao.findById(userId);
		String rs="n";
			if("0".equals(uu.getUserRole()) || "3".equals(uu.getUserRole())){
				System.out.println("股东数据生成开始");
				//修改sys_user表角色
				SysUser.dao.updateUserRole("4",uu.getId());
				//查询对应分红方案
				Long dividendPlanId=Db.queryLong("select t.dividend_plan_id from dividend_plan t where t.create_company=? and t.dividend_plan_type='4'",uu.getCompanyId());
				//创建股东表
					Shareholder.dao.saveShareholder(getDate(),name,phone,0,0,dividendPlanId,uu.getId(),uu.getCompanyId());
				System.out.println("股东数据生成结束");
				rs="y";
			}
			Card cc= Card.dao.findCardByUserId(userId);
			if(null!=cc){
				if(null==cc.getUserOfShareholder() ||  "".equals(cc.getUserOfShareholder()) ){
					cc.setUserOfShareholder(userId);
					cc.setShareBy(userId);
					cc.setCardname("【"+uu.getName()+uu.getMobile()+"】茉德会员卡");
					cc.setCardcode(uu.getMobile());
					cc.setSharingNum(100);
					cc.update();
					CacheKit.remove(DicUtil.CACHE_CARD, userId);
					// 再查询有没有套餐
					Meal mm= Meal.dao.findShareMealById();
					Long mealId=mm.getMealId();//查询绑定默认套餐
					CardSetMeal cardSetMeal= CardSetMeal.dao.findMealOfCard2(mealId,cc.getCardid());
					if(null==cardSetMeal){
						System.out.println("该会员已有卡，但无默认套餐，只绑定套餐");
						Date now = new Date();
						Integer da=new Integer(mm.getMealValidity());
						Date startDate = DateUtils.addDays(now, da);
						CardSetMeal setMeal = new CardSetMeal();
						setMeal.setCardId(cc.getCardid());
						Integer n=new Integer(mm.getMealNumber());
						setMeal.setCardMealNumber(n);
						setMeal.setCardMealEndtime(startDate);
						setMeal.setCardMealId(new Date().getTime());
						setMeal.setCardSetMealId(mealId);
						setMeal.setCardMealSharenumber(mm.getMealSharenumber());
						setMeal.save();
						// 加入缓存中
						CacheKit.put(DicUtil.CACHE_CARD, cc.getCardid(), setMeal);
					}else {
						Integer n=new Integer(mm.getMealNumber());
						int aa=cardSetMeal.getCardMealNumber()+n;
						cardSetMeal.setCardMealNumber(aa);
						cardSetMeal.setCardMealSharenumber(mm.getMealSharenumber());
						cardSetMeal.update();
//						CacheKit.remove(DicUtil.CACHE_CARD_SET_MEAL, cardSetMeal.getCardSetMealId());//待问
					}
				}else{
					// 再查询有没有套餐
					Meal mm= Meal.dao.findShareMealById();
					Long mealId=mm.getMealId();//查询绑定默认套餐
					CardSetMeal cardSetMeal= CardSetMeal.dao.findMealOfCard2(mealId,cc.getCardid());
					if(null==cardSetMeal){
						System.out.println("该会员已有卡，但无默认套餐，只绑定套餐");
						Date now = new Date();
						Integer da=new Integer(mm.getMealValidity());
						Date startDate = DateUtils.addDays(now, da);
						CardSetMeal setMeal = new CardSetMeal();
						setMeal.setCardId(cc.getCardid());
						Integer n=new Integer(mm.getMealNumber());
						setMeal.setCardMealNumber(n);
						setMeal.setCardMealEndtime(startDate);
						setMeal.setCardMealId(new Date().getTime());
						setMeal.setCardSetMealId(mealId);
						setMeal.setCardMealSharenumber(mm.getMealSharenumber());
						setMeal.save();
						// 加入缓存中
						CacheKit.put(DicUtil.CACHE_CARD, cc.getCardid(), setMeal);
					}else {
						Integer n=new Integer(mm.getMealNumber());
						int aa=cardSetMeal.getCardMealNumber()+n;
						cardSetMeal.setCardMealNumber(aa);
						cardSetMeal.setCardMealSharenumber(mm.getMealSharenumber());
						cardSetMeal.update();
					}
				}

			}else {
				//新增一张卡逻辑
				Long cid=getDate().getTime();
				Card newCard=new Card();
				newCard.setCardid(cid);
				newCard.setCreateTime(new Date());
				newCard.setGroupid(uu.getCompanyId());
				newCard.setUserId(userId);
				newCard.setShareBy(userId);
				newCard.setUserOfShareholder(userId);
				newCard.setAvaiabletime(365);
				newCard.setIsshared("是");
				newCard.setSource("门店");
				newCard.setStatus("使用");
				newCard.setCardname("【"+uu.getName()+uu.getMobile()+"】茉德会员卡");
				newCard.setCardcode(uu.getMobile());
				CommonQuery cq=new CommonQuery();
				newCard.setCardTypeId(cq.fidCardTypeByUserIdAndCompany(uu.getCompanyId(),"4"));
				newCard.save();

				// 开始绑定套餐
				Meal mm= Meal.dao.findShareMealById();
				Long mealId=mm.getMealId();//默认套餐
				Date now = new Date();
				Integer da=new Integer(mm.getMealValidity());
				Date startDate = DateUtils.addDays(now, da);
				CardSetMeal setMeal = new CardSetMeal();
				setMeal.setCardId(cid);
				setMeal.setCardMealId(cid);
				setMeal.setCardSetMealId(mealId);
				Integer n=new Integer(mm.getMealNumber());
				setMeal.setCardMealNumber(n);
				setMeal.setCardMealEndtime(startDate);
				setMeal.setCardMealSharenumber(mm.getMealSharenumber());
				setMeal.save();
				CacheKit.put(DicUtil.CACHE_CARD,uu.getId(),newCard);
			}
			renderText(rs);

    }

	//获取人脉详情和总数初始化
	public void getMyCardPeople(){
		String userId = getUserCookie();
		String countNum=Card.dao.countCardTeamById(userId);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("cardTeamLs", Card.dao.findCardTeam(userId,0));
		jsonObject.put("countNum", countNum);
		renderJson(jsonObject);
	}

	//动态加载人脉详情
	public void getMyCardPeople2(){
		String userId = getUserCookie();
		int indexNum = getParaToInt("indexNum");
		List<Card> cardLs =Card.dao.findCardTeam(userId,indexNum*15);//e04f9f0468f441e39fcb799034286900
		indexNum=indexNum+1;
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("cardTeamLs",cardLs);
		jsonObject.put("indexNum", indexNum);
		renderJson(jsonObject);
	}
	/**
	 * 查看可分享会员卡套餐
	 */
	public void myCardMessage() {
		String type = getPara("type");
		String userId = getUserCookie();

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("user", SysUser.dao.findById(userId));
		jsonObject.put("page", Card.dao.myCardMeals2(userId));
		jsonObject.put("shop", SysOffice.dao.findShopByUserId(userId));
		renderJson(jsonObject);

	}
	/**
	 * 查看已过期、可使用的会员卡套餐
	 */
	public void myCardMeals() {
		String type = getPara("type");
		String userId = getUserCookie();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("user", SysUser.dao.findById(userId));
		jsonObject.put("page", Card.dao.myCardMeals(userId, type));
		jsonObject.put("shop", SysOffice.dao.findShopByUserId(userId));
		renderJson(jsonObject);

	}


	/**
	 * 点餐系统跨域查询用户是否有代金券
	 */
	public void findUserCoupon() {
		getResponse().addHeader("Access-Control-Allow-Origin", "*");
		String type = getPara("type");
		String userId = getUserCookie();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("page", Card.dao.myCardMeals(userId, type));
		String callback = getRequest().getParameter("callback");
		jsonObject.put("res", true);
		String jsonp = callback + "(" + JsonKit.toJson(jsonObject) + ")";
		renderJson(jsonp);
	}

	/**
	 * 查看已分享的会员卡
	 */
	public void vipCardSharedInfo() {
		String userId = getUserCookie();
		String userRole = SysUser.dao.findByIdInCache(userId).getUserRole();
		JSONObject jsonObject = getJsonObject();
		jsonObject.put("page", Card.dao.vipCardSharedInfo(userId, userRole));
		jsonObject.put("user", SysUser.dao.findByIdInCache(userId));
		renderJson(jsonObject);
	}

	/**
	 * 查看已分享的会员卡
	 */
	public void myConnection() {
		String userId = getUserCookie();
		String source = getPara("source");
		renderPageJson(Card.dao.getMyConnection(userId, source));
	}

	/**
	 * 领取会员卡套餐
	 */
	@Before(UserInter.class)

	public void receivedVipCard() {
		String shareholderId = getPara("shareholderId");
		String shareBy = getPara("sharedUserId");
		long mealId = getParaToLong("mealId");
		String userId = getUserCookie();
		JSONObject jsonObject = new JSONObject();
		if (shareBy.equals(userId)) {
			jsonObject.put("state", "0");
			System.out.println("不能领取自己分享的卡");
			jsonObject.put("message", "sorry!不能领取自己分享的卡~");
		} else {
			jsonObject = Card.dao.saveCardAndMeal(shareholderId, shareBy, mealId, userId);
			SysUser user = SysUser.dao.findByIdInCache(userId);
			if (user.getName() == null || user.getMobile() == null) {
				jsonObject.put("supplyInfo", "0");
				System.out.println("需补充用户信息");
			} else {
				jsonObject.put("supplyInfo", "1");
				System.out.println("信息完整");
			}
		}
		jsonObject.put("mealName", Meal.dao.findMealByIdInCache(mealId).getMealName());
		setAttr("jsonObject", jsonObject);
		render("/pages/page_receivedCoupon.html");
	}

	/**
	 * 关注公众号收到优惠券
	 */
	@Before(UserInter.class)
	public void receivedCoupon() {
		System.out.println("进入关注公众号收到优惠券");
		long mealId = getParaToLong("couponMealId");
		String userId = getUserCookie();
		JSONObject jsonObject = new JSONObject();
		jsonObject = Card.dao.saveCouponByFocus(mealId, userId);
		jsonObject.put("mealName", Meal.dao.findMealByIdInCache(mealId).getMealName());
		setAttr("jsonObject", jsonObject);
		render("/pages/page_receivedCouponByFocus.html");
	}

	/**
	 * 下单时判断顾客会员卡信息
	 * 
	 * @return
	 */
	public void getCardInfoByConsume() {
		String userId = getUserCookie();
		// String userId = "96da621d667e4cf8baeabc4fe187f9fc";
		Card cardInfo = Card.dao.findCardById(userId);
		renderJson(cardInfo);
	}

	public void cardConsume() {
		int price = getParaToInt("price");
		String orderNumber = getPara("orderId");
		String userId = getUserCookie();
		// String userId = "96da621d667e4cf8baeabc4fe187f9fc";
		Card cardInfo = Card.dao.findCardById(userId);
		System.out.println("cardInfo==null-----》"+ cardInfo==null);
		if (null == cardInfo) {
			renderErrorJson("会员卡扣款失败，请与收银台联系！");
		}else{
			System.out.println("card----》" + cardInfo.toJson());
			cardInfo.setAmt(cardInfo.getAmt().subtract(new BigDecimal(price)));
			cardInfo.update();
		}
		
		enhance(ShopOrder.class).paid(orderNumber, price, getUserCookie(), 1);
		redirect("/pages/page_userOrder/paidOrder.html");
		//render("/pages/page_paidOrder.html");
	}

}
